package tasks;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import main.Constants;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;


public class DeleteTask implements Taskable {

	private String relPath;
	private String filename;
	private String game;
	private String session;
	
	private int executeTry;

	public DeleteTask(String path, String filename, String game) {
		this.relPath = path;
		this.filename = filename;
		this.game = game;
		executeTry = 1;
		this.session = Constants.SESSION;
	}

	@Override
	public int start(Reportable context) {
		executeTry++;
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(Constants.HOST_URL+"delete_file.php");
		try {
			//request
			List<NameValuePair> paras = new ArrayList<NameValuePair>();
			paras.add(new BasicNameValuePair("session", this.session));
			paras.add(new BasicNameValuePair("game", game));
			paras.add(new BasicNameValuePair("path", relPath));
			paras.add(new BasicNameValuePair("filename", filename));
			paras.add(new BasicNameValuePair("output", "plain"));
			HttpEntity entity = new UrlEncodedFormEntity(paras, "UTF-8");
			post.setEntity(entity);
			
			//response
			HttpResponse res = client.execute(post);
			HttpEntity rEntity = res.getEntity();
			if(rEntity!=null){
				InputStream in = rEntity.getContent();
				BufferedReader rd = new BufferedReader(new InputStreamReader(in));
				String line;
				while((line=rd.readLine())!=null){
					if(line.startsWith("deleted")) {
						rEntity.consumeContent();
						return 0;
					}else rEntity.consumeContent();
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return -1;
	}

	@Override
	public String toString() {
		return "[delete: "+relPath+filename+"]";
	}

	@Override
	public int getTry() {
		return executeTry;
	}

	@Override
	public long getSize() {
		return 0;
	}

	@Override
	public String getPath() {
		return relPath+filename;
	}
	
}
